<?php

namespace app\api\middleware;

use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\SignatureInvalidException;
use think\Exception;

class Api
{
    public function handle($request, Closure $next){
        $status = 403;
        $message = "非法访问！";
        $header = $request->header();
        if (isset($header['authorization'])){
            $token = $header['authorization'];
            $secret = "me_clan";
            try{
                JWT::$leeway = 60;
                $data = JWT::decode($token,$secret,['HS256']);
                $request->user = $data;
            }catch (SignatureInvalidException $e){
                $message = '身份认证签名不正确';
                return json(['message'=>$message,'code'=>$status]);
            }catch (BeforeValidException $e){
                $message = '身份认证已过期,请重新登录';
                return json(['message'=>$message,'code'=>$status]);
            }catch (ExpiredException $e){
                $message = '身份认证已过期,请重新登录';
                return json(['message'=>$message,'code'=>$status]);
            }catch (Exception $e){
                $message = '非法访问！';
                return json(['message'=>$message,'code'=>$status]);
            }
        } else return json(['message'=>$message,'code'=>$status]);

        return $next($request);
    }
}